//
//  KINGPhotoBrowserController.swift
//  肉荣微博
//
//  Created by king on 15/8/8.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit
import SVProgressHUD

private let KINGPhotoBrowserCellIdentifier = "KINGPhotoBrowserCellIdentifier"

class KINGPhotoBrowserController: UIViewController {
    var urls:[NSURL]
    var index:Int
    
    init(urls:[NSURL], index:Int){
        self.urls = urls
        self.index = index
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    //这里讲的不是很明白, 这里需要进行设置，否则会造成切换之后有个间距
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //MARK: - 加上这些会导致控制器关闭的时候有跳动显现，去掉这里，collectionView不是用自动布局就可以解决图片之间添加空隙
//        var rect = UIScreen.mainScreen().bounds
//        rect.size.width += 20
//        view.frame = rect
    }
    override func loadView() {
        //让View变大、 宽度增加20，用于在切换图片的时候，中间有个间距
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setupUI()
        collectView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    private func setupUI() {
        //添加控件
        view.addSubview(collectView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //设置布局
        collectView.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["cv": collectView, "close":closeButton, "save":saveButton]
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        //将collectionView大小设置成和屏幕一样大小， 这样写就不能在viewDidLayoutSubviews中写代码了
        collectView.frame = view.bounds
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(100)]-(>=0)-[save(100)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        //添加方法
        closeButton.addTarget(self, action: "closeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "saveBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectView()
    }
    //配置控制器
    func prepareCollectView() {
        collectView.registerClass(KINGPhotoBrowserCell.self, forCellWithReuseIdentifier: KINGPhotoBrowserCellIdentifier)
        collectView.dataSource = self
        let flowLayout = collectView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.itemSize = view.bounds.size
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectView.pagingEnabled = true
    }
    //关闭控制器
    func closeBtnClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //保存按钮点击
    func saveBtnClick() {
        print(__FUNCTION__)
        //获取当前正在显示的indexPath
        let indexPath = collectView.indexPathsForVisibleItems().last!
        let cell = collectView.cellForItemAtIndexPath(indexPath) as! KINGPhotoBrowserCell
        guard let image = cell.imageView.image else {
            print("没有获取到图片")
            return
        }
        //将图片保存到相册中
        //函数名，然后是外部参数名，如果没有外部参数名，内部参数名也是一样的,中间不能有空格
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    //如果外部参数和内部参数一样， 他会提示我们要删除这个
    func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject?) {
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //懒加载控件
    private lazy var collectView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())//最后一定要加上（）不然会报错
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton:UIButton = UIButton(title: "下载", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    //记录当前缩放比例
    private var photoScale:CGFloat = 1
}

extension KINGPhotoBrowserController: UICollectionViewDataSource, KINGPhotoBrowserCellDelegate {
    //MARK: - UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectView.dequeueReusableCellWithReuseIdentifier(KINGPhotoBrowserCellIdentifier, forIndexPath: indexPath) as! KINGPhotoBrowserCell
        //cell.backgroundColor = UIColor.redColor()
        cell.url = urls[indexPath.item]
        cell.photoDelegate = self
        return cell
    }
    //MARK: - KINGPhotoBrowserCellDelegate
    func photoBrowserCellZoom(scale: CGFloat) {
        photoScale = scale
        //隐藏保存和关闭两个按钮，并且设置背景颜色
        hiddenContrls(scale < 1.0)
        if scale < 1.0 {
            //需要传入一个遵守UIViewControllerContextTransitioning 的对象
            //手动触发交互式转场
            startInteractiveTransition(self)
        } else {
            view.transform = CGAffineTransformIdentity
        }
    }
    func photoBrowserCellEndZoom() {
        //如果缩放比例小于0.8，关掉当前控制器
        if photoScale < 0.8 {
            completeTransition(true)
        } else {//否则，动画的回复到原来的状态
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                //回复到最初状态，
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                }, completion: { (_) -> Void in
                    //显示出保存和关闭按钮
                    self.photoScale = 1
                    self.hiddenContrls(false)
            })
        }
    }
    //返回当前正在显示的ImageView
    func currentImageView() -> UIImageView {
        let cell = collectView.cellForItemAtIndexPath(currentImageIndex()) as! KINGPhotoBrowserCell
        return cell.imageView
    }
    //放回当前显示的cell的indexPath，用这个indexpath算出最终应该回哪里去
    func currentImageIndex() -> NSIndexPath {
        return collectView.indexPathsForVisibleItems().last!
    }
    
    func hiddenContrls(hidden:Bool) {
        collectView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        closeButton.hidden = hidden
        saveButton.hidden = hidden
    }
}
//如果要实现交互式动画，就必须遵守这个协议
extension KINGPhotoBrowserController : UIViewControllerInteractiveTransitioning {
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        view.alpha = photoScale
    }
}

extension KINGPhotoBrowserController :UIViewControllerContextTransitioning {
    //返回容器视图。返回view.superView
    func containerView() -> UIView? { return view.superview }
    func isAnimated() -> Bool {return true}
    
    func isInteractive() -> Bool {return true}
    func transitionWasCancelled() -> Bool {return true}
    
    func presentationStyle() -> UIModalPresentationStyle {return UIModalPresentationStyle.Custom}
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    //当动画执行完成，需要做声明操作
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }

    func viewControllerForKey(key: String) -> UIViewController? {return self}
    
    func viewForKey(key: String) -> UIView? {return view}

    func targetTransform() -> CGAffineTransform {return CGAffineTransformIdentity}
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}

    func finalFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}
}
